<?php

/**
 * 自定义辅助函数.
 */
use Illuminate\Support\Facades\Log;

if (!function_exists('TransformDbConfig')) {
    /**
     * [TransformDbConfig 数据库连接配置文件转换].
     *
     * @Author   王文凡
     * @DateTime 2018-02-28
     *
     * @version  1.0
     *
     * @param array  $config [原数据]
     * @param string $prefix [表前缀]
     * @param string $driver [数据库类型]
     *
     * @return array|null
     */
    function TransformDbConfig(array $config = [], $prefix = '', $driver = 'mysql')
    {
        if ($config) {
            $db_config = [
                'driver' => $driver,
                'host' => $config['db_host'],
                'database' => $config['db_name'],
                'username' => $config['db_user'],
                'password' => $config['db_pw'],
                'charset' => $config['db_charset'],
                'collation' => 'utf8_unicode_ci',
                'prefix' => $prefix,
                'strict' => false,
            ];

            return $db_config;
        } else {
            return null;
        }
    }
}

if (!function_exists('arrayBriefness')) {
    /**
     * [arrayBriefness 二维转一维数组].
     *
     * @Author   王文凡
     * @DateTime 2018-02-28
     *
     * @version  1.0
     *
     * @param array  $array [原二维数组]
     * @param string $k     [生成的key]
     * @param string $v     [生成的value]
     *
     * @return array
     */
    function arrayBriefness($array, $k = '', $v = '')
    {
        $new_array = [0 => '请选择'];
        foreach ($array as $key => $value) {
            $new_array = array_merge($new_array, [$value[$k] => $value[$v]]);
        }

        return $new_array;
    }
}

if (!function_exists('verifySign')) {
    /**
     * [verifySign 支付签名].
     *
     * @Author   王文凡
     * @DateTime 2018-04-02
     *
     * @version  1.0
     *
     * @param array  $param [参数]
     * @param string $key   [支付key]
     *
     * @return string
     */
    function verifySign($param = [], $keySign)
    {
        if (isset($param['sign'])) {
            $param = array_remove($param, 'sign');
        }
        ksort($param);
        $rSign = '';
        foreach ($param as $key => $val) {
            if ('' != $val && !is_null($val)) {//空字符串和null不参与签名
                $rSign .= $key.'='.$val.'&';
            }
        }
        $rSign .= $keySign;
        $sign = md5($rSign);
        Log::info('pay_sign', [$rSign, $sign]);

        return $sign;
    }
}

if (!function_exists('setDB')) {
    /**
     * [setDB 动态设置数据库].
     *
     * @Author   王文凡
     * @DateTime 2018-04-02
     *
     * @version  1.0
     *
     * @param
     */
    function setDB($server_id, $db_type = 'all')
    {
        $base_db = [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'strict' => false,
            'engine' => null,
        ];
        $game_db = array_add($base_db, 'database', env('DB_DATABASE_GAME').$server_id);
        $game_log_db = array_add($base_db, 'database', env('DB_DATEBASE_GAME_LOG').$server_id);
        switch ($db_type) {
            case 'all':
                config(['database.connections.mysql_game' => $game_db]);
                config(['database.connections.mysql_game_log' => $game_log_db]);
                break;
            case 'game':
                config(['database.connections.mysql_game' => $game_db]);
                break;

            case 'log':
                config(['database.connections.mysql_game_log' => $game_log_db]);
                break;
            default:
                return false;
                break;
        }

        return true;
    }
}

if (!function_exists('array_remove')) {
    /**
     * [array_remove 根据key删除数组元素].
     *
     * @Author   王文凡
     * @DateTime 2018-04-23
     *
     * @version  1.0
     *
     * @param array  $data [数组]
     * @param string $key  [key]
     *
     * @return array
     */
    function array_remove($data, $key)
    {
        if (!array_key_exists($key, $data)) {
            return $data;
        }
        $keys = array_keys($data);
        $index = array_search($key, $keys);
        if (false !== $index) {
            array_splice($data, $index, 1);
        }

        return $data;
    }
}
if (!function_exists('httpResponse')) {
    /**
     * [httpResponse api响应结构].
     *
     * @Author   王文凡
     * @DateTime 2018-04-23
     *
     * @version  1.0
     *
     * @param int    $code [description]
     * @param string $msg  [description]
     * @param array  $data [description]
     *
     * @return [type] [description]
     */
    function httpResponse($code = 200, $msg = 'success', $data = [])
    {
        return [
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
        ];
    }
}

if (!function_exists('checkSign')) {
    /**
     * [verifySign 对外api接口签名].
     *
     * @Author   王文凡
     * @DateTime 2018-04-02
     *
     * @version  1.0
     *
     * @param array  $param [参数]
     * @param string $key   [key]
     *
     * @return string
     */
    function checkSign($param = [], $key = '')
    {
        $param = array_remove($param, 'sign');
        ksort($param);
        $str = '';
        foreach ($param as $k => $v) {
            $str .= $v;
        }

        return md5($str.$key);
    }
}

if (!function_exists('floatPercent')) {
    /**
     * [floatPercent 小数转百分数].
     *
     * @Author   王文凡
     * @DateTime 2018-04-26
     *
     * @version  1.0
     *
     * @param [type] $number [description]
     *
     * @return [type] [description]
     */
    function floatPercent($number = 0)
    {
        if (0 == $number) {
            return 0;
        }
        $str = round($number, 4);

        return $str * 100 .'%';
    }
}

if (!function_exists('getVIP')) {
    /**
     * [getVIP 获取vip等级].
     *
     * @Author   王文凡
     * @DateTime 2018-05-09
     *
     * @version  1.0
     *
     * @param int $money [仙晶数量]
     *
     * @return string
     */
    function getVIP($money)
    {
        if ($money > 1 && $money < 60) {
            return 'VIP0';
        } elseif ($money >= 60 && $money < 300) {
            return 'VIP1';
        } elseif ($money >= 300 && $money < 1000) {
            return 'VIP2';
        } elseif ($money >= 1000 && $money < 2000) {
            return 'VIP3';
        } elseif ($money >= 2000 && $money < 5000) {
            return 'VIP4';
        } elseif ($money >= 5000 && $money < 10000) {
            return 'VIP5';
        } elseif ($money >= 10000 && $money < 20000) {
            return 'VIP6';
        } elseif ($money >= 20000 && $money < 50000) {
            return 'VIP7';
        } elseif ($money >= 50000 && $money < 100000) {
            return 'VIP8';
        } elseif ($money >= 100000 && $money < 200000) {
            return 'VIP9';
        } elseif ($money >= 200000 && $money < 300000) {
            return 'VIP10';
        } elseif ($money >= 300000 && $money < 500000) {
            return 'VIP11';
        } elseif ($money >= 500000 && $money < 800000) {
            return 'VIP12';
        } elseif ($money >= 800000 && $money < 1000000) {
            return 'VIP13';
        } elseif ($money >= 1000000 && $money < 1500000) {
            return 'VIP14';
        } elseif ($money >= 1500000) {
            return 'VIP12';
        }

        return 'VIP0';
    }
}

if (!function_exists('getChannel')) {
    /**获取聊天频道.
     * @param  number $channel
     * @return string
     */
    function getChannel($channel)
    {
        switch ($channel) {
            case '0': return '系统频道';
                break;
            case '1': return '世界频道';
                break;
            case '2': return '工会频道';
                break;
            case '3': return '私聊频道';
                break;
            case '4': return '队伍频道';
                break;
            case '5': return '普通频道';
                break;
            case '6': return '地图频道';
                break;
            case '7': return '喇叭频道';
            default: return '未知';
        }
    }
}

if (!function_exists('arrayNumericString')) {
    /**
     * 整型数组转值转字符串.
     *
     * @param array $array
     *
     * @return array
     */
    function arrayNumericString(array $array = [])
    {
        if (empty($array)) {
            return $array;
        }
        $new_array = array_map(function ($v) {
            return (string) $v;
        }, $array);

        return $new_array;
    }
}

if (!function_exists('create_unique')) {
    /**生成唯一订单号
     * @return string
     */
    function create_unique()
    {
        return date('Ymd').str_pad(mt_rand(1, 999999999999999999), 5, '0', STR_PAD_LEFT);
    }
}

if (!function_exists('getActivityName')) {
    /**
     * 根据活动id获取活动名.
     *
     * @param $id
     *
     * @return string
     */
    function getActivityName($id)
    {
        if(!$id){
            return "未知活动";
        }
        if ($name = config('game.activity')[$id]) {
            return $name;
        }

        return '未知活动';
    }
}

if (!function_exists('getProfession')) {
    /**
     * 获取职业.
     *
     * @param $id
     *
     * @return string
     */
    function getProfession($id)
    {
        switch ($id) {
            case '1': return '战士';
                break;
            case '2': return '影刹';
                break;
            case '3': return '法师';
                break;
            default:  return '未知';
        }
    }
}

if (!function_exists('levelConvert')) {
    /**
     * 等级转换为等级阶段.
     *
     * @param $level
     *
     * @return int
     */
    function levelConvert($level)
    {
        $length = strlen($level);
        if (1 == $length) {
            return 1;
        } else {
            $number = substr($level, 0, 1);
            for ($i = 1; $i < $length; ++$i) {
                $number .= '0';
            }

            return intval($number);
        }
    }
}

if (!function_exists('thanLevel')) {
    /**
     * 获取大于当前等级的所有玩家数量.
     *
     * @param $level_list
     * @param $level
     *
     * @return int
     */
    function thanLevel($level_list, $level)
    {
        if (empty($level_list)) {
            return 0;
        }
        $number = 0;
        foreach ($level_list as $lv) {
            if ($lv->level >= $level) {
                $number += $lv->level_number;
            }
        }

        return $number;
    }
}

if (!function_exists('lessLevel')) {
    /**
     * 获取.
     *
     * @param $level_list
     * @param $level
     *
     * @return int
     */
    function lessLevel($level_list, $level)
    {
        if (empty($level_list)) {
            return 0;
        }
        $number = 0;
        foreach ($level_list as $lv) {
            if ($lv->level <= $level) {
                $number += $lv->level_number;
            }
        }

        return $number;
    }
}

if (!function_exists('xmlToArray')) {
    /**
     * xml转数组.
     *
     * @param $xml
     *
     * @return mixed
     */
    function xmlToArray($xml)
    {
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement',
            LIBXML_NOCDATA)), true);

        return $values;
    }
}

if (!function_exists('ConvertPublicKey')) {
    function ConvertPublicKey($public_key)
    {
        $public_key_string = '';
        $count = 0;
        for ($i = 0; $i < strlen($public_key); ++$i) {
            if ($count < 64) {
                $public_key_string .= $public_key[$i];
                ++$count;
            } else {
                $public_key_string .= $public_key[$i]."\r\n";
                $count = 0;
            }
        }
        $public_key_header = "-----BEGIN PUBLIC KEY-----\r\n";
        $public_key_footer = "\r\n-----END PUBLIC KEY-----";
        $public_key_string = $public_key_header.$public_key_string.$public_key_footer;

        return $public_key_string;
    }
}

if (!function_exists('http_build_query_noencode')) {
    function http_build_query_noencode($queryArr)
    {
        if (empty($queryArr)) {
            return '';
        }
        $returnArr = [];
        foreach ($queryArr as $key => $value) {
            $returnArr[] = $key.'='.$value;
        }

        return implode('&', $returnArr);
    }
}

if (!function_exists('PublickeyDecodeing')) {
    function PublickeyDecodeing($crypttext, $publickey)
    {
        $pubkeyid = openssl_get_publickey($publickey);
        if (openssl_public_decrypt($crypttext, $sourcestr, $pubkeyid, OPENSSL_PKCS1_PADDING)) {
            return $sourcestr;
        }

        return false;
    }
}

if (!function_exists('getFindType')) {
    function getFindType($params)
    {
        if (empty($params)) {
            return 1;
        }
        if (isset($params['platform_id']) && $params['platform_id'] > -1 && isset($params['channel_id']) && $params['channel_id'] >= -1) {
            if (isset($params['server_id']) && $params['server_id'] > -1) {
                return 4;
            } else {
                return 2;
            }
        }
        if (isset($params['server_id']) && $params['server_id'] >= -1) {
            return 3;
        }
        if (isset($params['platform_id']) && -1 == $params['platform_id']) {
            return 1;
        }

        return 1;
    }
}
